const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${[year, month, day].map(formatNumber).join('-')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
/*
 *微信小程序的数据请求的再次封装
 */

const wxajax = (url, method, data) => {
  let baseurl = ''
  if (typeof __wxConfig == "object") {
    const version = __wxConfig.envVersion;
    // const version = "trial";
    if (version == "develop") {
      // baseurl = "http://localhost" + url
      baseurl = "https://jutuikedev.ti132520.fun" + url
    } else if (version == "trial") {
      baseurl = "https://jutuikedev.ti132520.fun" + url
    } else if (version == "release") {
      baseurl = "https://jutuike.ti132520.fun" + url
    } else {
      baseurl = dev_url + url
    }
  } else {
    baseurl = dev_url + url
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: baseurl,
      data: data,
      header: {
        "content-type": method == 'get' ? 'application/json' : 'application/x-www-form-urlencoded',
        "Accept": 'application/json',
        "APPID": wx.getAccountInfoSync().miniProgram.appId,
        "OPENID": wx.getStorageSync('openid') == "" ? "" : wx.getStorageSync('openid')
      },
      method: method,
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        if (res.data.code == 300) {
          wx.reLaunch({
            url: "/pages/none/none?msg=" + res.data.msg
          })
          return
        }
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
}

// 图片上传请求
const wxuploadFile = (url, filrobj) => {
  let baseurl = "https://jutuikedev.ti132520.fun" + url

  // let baseurl = "http://localhost"+ url // 测试接口
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      filePath: filrobj,
      name: 'file',
      url: baseurl,
      header: {
        "content-type": "multipart/form-data",
        "Accept": 'application/json',
        "APPID": wx.getAccountInfoSync().miniProgram.appId,
        "OPENID": wx.getStorageSync('openid') == "" ? "" : wx.getStorageSync('openid')
      },
      success: function (res) {
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
}
/*
 *微信小程序alert弹出的封装
 */
const wxshowtoast = (star, icon) => {
  wx.showToast({
    title: star,
    icon: icon ? icon : "none",
    duration: 1000
  })
}
const showLoading = (star) => {
  wx.showLoading({
    title: star
  })
}


module.exports = {
  formatTime,
  wxajax,
  wxshowtoast,
  showLoading,
  wxuploadFile
}
